package com.mingweicai.intergration.test;

import java.lang.reflect.Method;
import java.util.Map;
import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.CallbackFilter;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.cglib.proxy.NoOp;

public class CallbackFilterDemo {
  public static void main(String[] args) {
    
    Callback[] callbacks = new Callback[] {
        new MethodInterceptorImpl(), NoOp.INSTANCE
    };

    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(MyClass.class);
    enhancer.setCallbacks(callbacks);
    enhancer.setCallbackFilter(new CallbackFilterImpl());

    MyClass myClass = (MyClass) enhancer.create();

    myClass.method();

    myClass.method1();
  }

  private static class CallbackFilterImpl implements CallbackFilter {

    @Override
    public int accept(Method method) {
      if (method.getName().equals("method"))
        return 1;
      else
        return 0;
    }

  }

  private static class MethodInterceptorImpl implements MethodInterceptor {

    @Override
    public Object intercept(Object obj, Method method, Object[] args,
        MethodProxy proxy) throws Throwable {
      System.err.println("Before invoke " + method);
      Object result = proxy.invokeSuper(obj, args);
      System.err.println("After invoke" + method);
      return result;
    }

  }
}

class MyClass {
  public void method() {
    method1();
    System.out.println("-------------------------------------");
  }

  public void method1() {
    System.out.println("MyClass.method()1");
  }
}